# encoding: utf-8
import os

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext.db import djangoforms

import functions

class Post(db.Model):
    """A Post category"""
    title = db.StringProperty(required=True)
    content = db.TextProperty(required=True)
    excerpt = db.StringProperty()
    permalink = db.StringProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    modified = db.DateTimeProperty(auto_now=True)
    published = db.DateTimeProperty()
    creator = db.UserProperty(required=True)
    categories_keys = db.ListProperty(db.Key)
    draft = db.BooleanProperty(required=True, default=True)
    post_type = db.StringProperty(required=True, choices=set(["page", "post"]), default="post")
    comments_enabled = db.BooleanProperty(required=True, default=True)
    num_comments = db.IntegerProperty(required=True, default=0)

    def post_comment(self, data, ip):
        author = data['author']
        email = data['email']
        text = data['text']
        new_coment = Comment(parent=self, author=author, email=email, text=text)
        new_coment.parent = self
        new_coment.post = self
        new_coment.ip = ip
        new_coment.put()
        self.num_comments += 1
        self.put()
    
    _categories = None
    
    @property
    def categories(self):
        """The list of categories of a post.
        
        The value is expensive to compute, so it is cached.
        """
        if self._categories is None:
            if len(self.categories_keys) > 0:
                self._categories = db.get(self.categories_keys)
            else:
                self._categories = ()
        return self._categories
   
    def delete(self): 
        for comment in self.comments: 
            comment.delete()
        if not self.draft:
            functions.decrement_counter('global_' + self.post_type + '_counter')
            for cat in self.categories:
                functions.decrement_counter('cat_' + cat.category_url + '_counter')
        super(Post, self).delete()

    
class Category(db.Model):
    """"""
    category_name = db.StringProperty(required=True)
    category_url = db.StringProperty(required=True)
    
    @property 
    def posts_in_category(self): 
        return Post.gql('WHERE categories_keys = :1 ', self.key())
    
    def delete(self):
        functions.del_counter('cat_' + self.category_url + '_counter')
        for post in self.posts_in_category: 
            post.categories_keys.remove(self.key()) 
            post.put() 
        super(Category, self).delete()
        

class Comment(db.Model):
    """A Comment for a specific post. """
    post = db.ReferenceProperty(Post, collection_name='comments')
    ip = db.StringProperty()
    date = db.DateTimeProperty(auto_now=True)
    author = db.StringProperty(required=True)
    email = db.EmailProperty(required=True)
    link = db.LinkProperty()
    text = db.TextProperty(required=True)
    type = db.StringProperty(required=True, choices=set(["comment", "trackback"]), default="comment")
    
    def delete(self):
        functions.decrement_counter('global_comments_counter')
        super(Comment, self).delete()
    
class CommentForm(djangoforms.ModelForm):
    class Meta:
        model = Comment
        exclude = ['ip','post','type']

class Link(db.Model):
    name = db.StringProperty(required=True)
    link = db.LinkProperty(required=True)
    created = db.DateTimeProperty(auto_now_add=True)
    modified = db.DateTimeProperty(auto_now=True)
    

class LinkForm(djangoforms.ModelForm):
    class Meta:
        model = Link
        
  
class CachedPage(db.Model):
    """docstring for CachedPage"""
    html = db.BlobProperty()
    type = db.StringProperty()
    content_type = db.StringProperty(default='text/html')
    created = db.DateTimeProperty(auto_now_add=True)
    

class SidebarWidget(db.Model):
    name = db.StringProperty(required=True)
    title = db.StringProperty()
    text = db.TextProperty(required=True)
    created = db.DateTimeProperty(auto_now_add=True)
    modified = db.DateTimeProperty(auto_now=True)    

class SidebarWidgetForm(djangoforms.ModelForm):
    class Meta:
        model = SidebarWidget

class Option(db.Model):
    label = db.StringProperty(required=True)
    name = db.StringProperty(required=True)
    value = db.StringProperty()
    option_type = db.StringProperty(required=True, choices=set(['int', 'str', 'boolean', 'list']), default='int')
    space = db.StringProperty(required=True, default = 'global')
    created = db.DateTimeProperty(auto_now_add=True)
    modified = db.DateTimeProperty(auto_now=True)    
       
    @property
    def html(self):
        if self.option_type == 'boolean':
            str ='<input type="checkbox" name="%s" value="True" id="%s" ' % (self.name, self.name) 
            if self.value == 'True':
                str = str + 'checked="checked"'
            str = str + ' >'
            return str
        else:
            value = ''
            if self.value:
                value = self.value
            return '<input type="text" name="%s" value="%s" id="%s" />' % (self.name, value, self.name)

class Counter(db.Model):
    name = db.StringProperty(required=True)
    count = db.IntegerProperty(required=True, default=0)
